/* Copyright (C) 2007-2008  klevgert  http://code.google.com/p/db4o-netbeans/

This file is part of the db4o-netbeans module suite.

db4o-netbeans is free software; you can redistribute it and/or modify it under
the terms of version 2 of the GNU General Public License as published
by the Free Software Foundation.
 
db4o-netbeans is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. */

package com.db4o.nb.dialogs;

import com.db4o.ObjectContainer;
import com.db4o.nb.util.ClassLoaderUtil;
import com.db4o.nb.util.PreferencesUtil;
import com.db4o.reflect.ReflectClass;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;

/**
 *
 * @author  klevgert
 */
public class SelectTypeDialog extends javax.swing.JDialog {
  
  /** A return status code - returned if Cancel button has been pressed */
  public static final int RET_CANCEL = 0;
  /** A return status code - returned if OK button has been pressed */
  public static final int RET_OK = 1;
  
  private int returnStatus = RET_CANCEL;
  private String selectedClass = "";
  private ObjectContainer objectContainer;
  
  Thread readThread;
  
  /** Creates new form SelectTypeDialog */
  public SelectTypeDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    
    final DefaultTreeModel scanModel = new DefaultTreeModel(new DefaultMutableTreeNode("Scanning..."));
    treeTypes.setModel(scanModel);

    Runnable runnable = new Runnable() {
      public void run() {
        
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        addClassesFromDatabase(root);
        addLibrariesFromPreferences(root);
        addLibrariesFromClasspath(root);    

        final DefaultTreeModel model = new DefaultTreeModel(root);

        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            treeTypes.setModel(model);
            okButton.setEnabled(true);
          }
        });
        
        SelectTypeDialog.this.treeTypes.setModel(model);
      }
    };
    readThread = new Thread(runnable);
    readThread.start();
    
  }
  
  public ObjectContainer getObjectContainer() {
    return this.objectContainer;
  }
  
  public void setObjectContainer(ObjectContainer oc ) {
    this.objectContainer = oc;
  }
  
  /** @return the return status of this dialog - one of RET_OK or RET_CANCEL */
  public int getReturnStatus() {
    return returnStatus;
  }
  
  public String getSelectedClass() {
    return selectedClass;
  }
  
  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
  private void initComponents() {
    okButton = new javax.swing.JButton();
    cancelButton = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    treeTypes = new javax.swing.JTree();

    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        closeDialog(evt);
      }
    });

    okButton.setText("OK");
    okButton.setEnabled(false);
    okButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        okButtonActionPerformed(evt);
      }
    });

    cancelButton.setText("Cancel");
    cancelButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cancelButtonActionPerformed(evt);
      }
    });

    jLabel1.setText("Select Type:");

    treeTypes.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
      public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
        treeTypesValueChanged(evt);
      }
    });

    jScrollPane1.setViewportView(treeTypes);

    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(layout.createSequentialGroup()
        .addContainerGap()
        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
          .add(layout.createSequentialGroup()
            .add(jLabel1)
            .addContainerGap(358, Short.MAX_VALUE))
          .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
            .add(okButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 67, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(cancelButton)
            .add(20, 20, 20))
          .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE)
            .addContainerGap())))
    );

    layout.linkSize(new java.awt.Component[] {cancelButton, okButton}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

    layout.setVerticalGroup(
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(layout.createSequentialGroup()
        .addContainerGap()
        .add(jLabel1)
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
          .add(cancelButton)
          .add(okButton))
        .addContainerGap())
    );
    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void treeTypesValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_treeTypesValueChanged
// TODO add your handling code here:
    
  }//GEN-LAST:event_treeTypesValueChanged
  
  private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
   
    if( treeTypes.getSelectionCount() > 0) {
      selectedClass = (String) treeTypes.getSelectionPath().getLastPathComponent().toString();
    }
    doClose(RET_OK);
    
  }//GEN-LAST:event_okButtonActionPerformed
  
  private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
    doClose(RET_CANCEL);
    
    try {
      if( readThread.isAlive() ) {
        readThread.join(10000);
      }
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }
    
  }//GEN-LAST:event_cancelButtonActionPerformed
  
  /** Closes the dialog */
  private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
    doClose(RET_CANCEL);
  }//GEN-LAST:event_closeDialog
  
  private void doClose(int retStatus) {
    returnStatus = retStatus;
    setVisible(false);
    dispose();
  }

  private void addClassesFromDatabase(final DefaultMutableTreeNode root) {
    
    try {
      DefaultMutableTreeNode dbNode = new DefaultMutableTreeNode("Database");
      root.add(dbNode);
      
      ReflectClass[] classes = this.objectContainer.ext().knownClasses();
      for (int i = 0; i < classes.length; i++) {
        String clsName = classes[i].getName();
        if( !PreferencesUtil.isSuppressedPackage(clsName) ){
          DefaultMutableTreeNode node = new DefaultMutableTreeNode(clsName);
          dbNode.add(node);
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  private void addLibrariesFromPreferences(final DefaultMutableTreeNode root) {
    
    String[] prefLibs = PreferencesUtil.getSpecifiedLibraries();
    for (int i = 0; i < prefLibs.length; i++) {
      addClassesFromJar(prefLibs[i], root);
    }
  }


  private void addLibrariesFromClasspath(final DefaultMutableTreeNode root) {
    String classpath = System.getenv("CLASSPATH");
    String[] libs = classpath.split(";");
    for (int i = 0; i < libs.length; i++) {
      addClassesFromJar(libs[i], root);
    }
  } 
  
  private void addClassesFromJar(final String jarFile, final DefaultMutableTreeNode root) {
    try {
      JarFile jar = new JarFile(jarFile);
      DefaultMutableTreeNode jarNode = new DefaultMutableTreeNode(jarFile);
      root.add(jarNode);
      
      Enumeration enumeration = jar.entries();
      while( enumeration.hasMoreElements() ) {
        JarEntry jarEntry = (JarEntry) enumeration.nextElement();
        String name = jarEntry.getName();
        if (name.indexOf(".class") > 0 && !(name.indexOf("$") > 0)) {
          String clsName = name.substring(0, name.lastIndexOf(".")).replace('/', '.');
          if( !PreferencesUtil.isSuppressedPackage(clsName) ){
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(clsName);
            jarNode.add(node);
          }
        }
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
    
  
  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        new SelectTypeDialog(new javax.swing.JFrame(), true).setVisible(true);
      }
    });
  }
  
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton cancelButton;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JButton okButton;
  private javax.swing.JTree treeTypes;
  // End of variables declaration//GEN-END:variables
  
  
}
